package com.heima.wemedia.service.impl;

import com.alibaba.nacos.common.util.Md5Utils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.media.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Override
    public WmUser findByName(String name) {
//        LambdaQueryWrapper<WmUser> query = new LambdaQueryWrapper<>();
//        if (name!=null){
//            query.like(WmUser::getName,name);
//        }
//        WmUser wmUser = getOne(query);
        List<WmUser> list = list(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, name));
        if (list!=null&&!list.isEmpty()){
            return list.get(0);
        }
        return null;
    }

    /**
     * 登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDto dto) {
        // 参数检查
        if (dto==null||dto.getName()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 获取数据库中的数据对象

        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (wmUser==null){
            return ResponseResult.okResult("用户不存在");
        }
        String pwdInput = Md5Utils.getMD5((dto.getPassword() + wmUser.getSalt()).getBytes());
        if (pwdInput.equals(wmUser.getPassword())){
            // 验证成功
            // 创建jwt并返回
            Map<String,Object> map = new HashMap<>();
            // 将核心信息置空
            wmUser.setPassword("");
            wmUser.setSalt("");
            map.put("user",wmUser);
            //创建jwt
            String token = AppJwtUtil.getToken(wmUser.getId().longValue());
            map.put("token", token);
            //返回数据

            return ResponseResult.okResult(map);

        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"密码错误");
        }
    }
}
